<?php

namespace app\common\model;;

use think\Model;

class TradeListModel extends BaseModel{

	protected $table = 'tp_trade_list';

	public function addData($uid,$cid,$type,$amount,$price,$rate,$fee){
		$data = [
			'uid'=>$uid,
			'cid'=>$cid,
			'type'=>$type,
			'amount'=>$amount,
			'left_amount'=>$amount,
			'rate'=>$rate,
			'fee'=>$fee,
			'price'=>$price,
			'status'=>1,
			'date'=>$this->getTime()
		];
		$res = $this->insert($data);
		return $res;
	}

	/*
	获取订单
	 */
	public function getOrder($uid,$cid='',$type=1,$page=1){
		if($cid){
			$where = 'o.cid='.$cid;
		} else {
			$where = '1=1';
		}
		$type = $type==2?0:1;
		$data = $this->alias('o')
					->join('tp_user u','u.id=o.uid')
					->join('tp_pay_info p','o.uid=p.uid','LEFT')
					->join('tp_coin c','c.id=o.cid','LEFT')
					->where('o.uid','<>',$uid)
					->where('o.type',$type)
					->where('o.status',1)
					->where('u.status',1)
					->where($where)
					->order('o.id asc')
					->limit(10)
					->page($page)
					->field('o.*,u.username,p.weixin,p.alipay,p.card,c.name c_name,c.icon c_img')

					//->fetchSql(true)
					->select();
		return $data;
	}

	/*
	获取自身订单
	 */
	public function getSelfOrder($uid,$cid=''){
		if($cid){
			$where = 'o.cid='.$cid;
		} else {
			$where = '1=1';
		}
		$data = $this->alias('o')
						->join('tp_coin c','o.cid=c.id','LEFT')
						->where('o.uid',$uid)
						->where($where)
						->order('o.status asc')
						->order('date desc')
						->field('o.*,c.name c_name,c.icon c_img')
						->select();
		return $data;
	}

	/*
	订单详情
	 */
	public function orderDetail($id){
		$data = $this->alias('o')
					->join('tp_user u','u.id=o.uid')
					//->join('nc_trade_record t','o.uid=t.sell_uid or o.uid=t.buy_uid','LEFT')
					->join('tp_pay_info p','o.uid=p.uid','LEFT')
					->where('o.id',$id)
					->field('o.*,u.username,u.avatar,p.weixin,p.alipay,p.card')
					//->fetchSql(true)
					->find();
		return $data;
	}

	public function getOrderInfo($id){
		$data = $this->where('id',$id)->lock(true)->find();
		return $data;
	}

	/*
	更新订单
	 */
	public function updateRecord($id,$amount){
		$info = $this->where('id',$id)->find();
		if($info['left_amount']<$amount || $amount==0){
			return false;
		}
		if($info['left_amount']>$amount){
			$res = $this->where('id',$id)->update([
				'left_amount' => $info['left_amount']-$amount
			]);
		} else {
			$res = $this->where('id',$id)->update([
				'left_amount' => 0,
				'status' => 3
			]);
		}
		return $res;
	}

	/*
	更新订单状态
	 */
	public function updateStatus($id,$status){
		$res = $this->where('id',$id)->update([
			'status'=>$status
		]);
		return $res;
	}
}